import json
import os
import random
from pathlib import Path

from django.core import management
from django.db import transaction
from faker import Faker
from model_bakery import baker

from album.models import Album
from articles.models import Article, Tag, Folder
from authentication.models import User
from core.file_import.import_factory import ImportFactory
from expense.models import PayCategory
from system.models import Iconfont
from timeline.models import LifeRecord, LifeRecordImage
from toolkit.models import Toolkit

fake = Faker(['zh_CN'])
BASE_DIR = Path(__file__).resolve(strict=True).parent  # os.path.abspath(os.path.dirname(__file__))  # 获取当前路径
ROOT_DIR = BASE_DIR.parent.parent.parent.parent


class Command(management.BaseCommand):
    help = '清空数据库后，初始化数据'

    def add_arguments(self, parser):
        parser.add_argument('--init', '-i', action='append', default=[], help='初始化的功能列表')
        parser.add_argument('username', help='admin的用户名')
        parser.add_argument('password', help='admin的密码')
        parser.add_argument('-pro', action='store_true', help='初始化环境是否为生产环境')
        parser.add_argument('-all', action='store_true', help='执行所有的初始化方法')

    def handle(self, *args, **kwargs):

        with transaction.atomic():
            # DELETE FROM pg_trigger WHERE tgname like 'denorm_after_row_%';    触发器已经存在
            management.call_command('flush', verbosity=0, interactive=False)

            demo = User.objects.create_superuser(username='demo123@qq.com', password='demo', nickname='Demo')
            admin = User.objects.create_superuser(username=kwargs['username'], password=kwargs['password'],
                                                  nickname='Liu PFei')
            kwargs['demo'] = demo
            kwargs['admin'] = admin

            init = self.all_init_methods() if kwargs['all'] else kwargs['init']
            with transaction.atomic():
                for fun_name in init:
                    fun = getattr(self, fun_name)
                    fun(**kwargs)

            text = '生产环境数据初始化成功' if kwargs['pro'] else '开发环境数据初始化成功'
            self.stdout.write(self.style.SUCCESS(text))

    def all_init_methods(self):
        # 获取所有的初始化方法
        return list(filter(lambda m: m.startswith("init_") and callable(getattr(self, m)), dir(self)))

    def init_expense(self, **kwargs):
        # 消费, 开发环境才会执行
        if kwargs['pro']:
            return

        class Request:
            user = kwargs['demo']

        request = Request()

        factory = ImportFactory()
        alipay_bill = os.path.join(ROOT_DIR, 'const/alipay_bill.csv')
        factory.get_import('AliPayBill', alipay_bill).save(request=request)
        wechat_bill = os.path.join(ROOT_DIR, 'const/wechat_bill.csv')
        factory.get_import('WeChatBill', wechat_bill).save(request=request)

        paycategorys = """[
                  {"icon": "zhufangbutie", "name": "住房补贴", "color": "#249af5", "sort": 0, "pay_type": "income"}, 
                  {"icon": "benyueshouruyugu", "name": "工资", "color": "#FFC107", "sort": 0, "pay_type": "income"}, 
                  {"icon": "tableware", "name": "美食", "color": "#249af5", "sort": 0, "pay_type": "spending"},
                  {"icon": "liwuhuodong", "name": "礼物", "color": "#DC3F74F2", "sort": 0, "pay_type": "spending"}, 
                  {"icon": "xihuan", "name": "父母", "color": "#F80000", "sort": 0, "pay_type": "spending"},
                  {"icon": "shouye", "name": "护肤", "color": "#ECB50F", "sort": 0, "pay_type": "spending"}, 
                  {"icon": "tongxun", "name": "话费", "color": "#00BCD4B3", "sort": 0, "pay_type": "spending"},
                  {"icon": "zhufang", "name": "房租", "color": "#A07157A3", "sort": 0, "pay_type": "spending"}, 
                  {"icon": "shu", "name": "学习", "color": "#4424F5", "sort": 0, "pay_type": "spending"}, 
                  {"icon": "hanglixiang", "name": "旅行", "color": "#164060", "sort": 0, "pay_type": "spending"},
                  {"icon": "qunzi", "name": "女装", "color": "#F524A7", "sort": 0, "pay_type": "spending"},
                  {"icon": "clothes", "name": "男装", "color": "#030000", "sort": 0, "pay_type": "spending"},
                  {"icon": "yiliao", "name": "生病", "color": "#388DCE", "sort": 0, "pay_type": "spending"},
                  {"icon": "shuiguo", "name": "水果", "color": "#F52424", "sort": 0, "pay_type": "spending"},
                  {"icon": "tongchengwaimai", "name": "外卖", "color": "#8BC34AD9", "sort": 0, "pay_type": "spending"},
                  {"icon": "zihangche", "name": "交通出行", "color": "#24E6F5", "sort": 0, "pay_type": "spending"}, 
                  {"icon": "shengxian-xianshucai", "name": "买菜", "color": "#18A61ECC", "sort": 0, "pay_type": "spending"},
                  {"icon": "ershouhuishou","name": "转账", "color": "#F2C806", "sort": 0, "pay_type": "transfer"}]"""

        PayCategory.objects.bulk_create(
            [PayCategory(**paycategory, created_by=kwargs['admin']) for paycategory in json.loads(paycategorys)])

    def init_timeline(self, **kwargs):
        class Request:
            user = kwargs['demo']

        request = Request()
        factory = ImportFactory()
        alipay_bill = os.path.join(ROOT_DIR, 'const/timeline.xlsx')
        factory.get_import('TimeLine', alipay_bill).save(request=request)

        for i in range(50):
            images = []
            for j in range(random.choice([0, 2, 0, 5, 9])):
                images.append(LifeRecordImage(image=f'https://picsum.photos/seed/{i * j}/160/320'))
            images = LifeRecordImage.objects.bulk_create(images)
            obj = LifeRecord.objects.create(content=fake.paragraph(), created_by=kwargs['demo'])
            obj.images.add(*images)

    def init_album(self, **kwargs):
        # 相册
        for i in range(8):
            album = Album.objects.create(name=f'album-{i}', created_by=kwargs['demo'])
            num = 40 if i == 0 else 2
            for j in range(0, num):
                baker.make('album.Picture', image=f'https://picsum.photos/seed/{i + j}/200/300', album=album)

    def init_toolkit(self, **kwargs):
        toolkits = [{'name': '随机图片网站', 'url': 'https://picsum.photos/', 'describe': '获取指定大小的随机图片'},
                    {'name': 'Smarty5', 'url': 'https://smarty.stepofweb.com/5.0.0/html_frontend/index.html',
                     'describe': 'Smarty 是市场上唯一不需要 Javascript 和 CSS 编码的模板！'},
                    {'name': '免费Logo制作', 'url': 'https://myfreelogomaker.com', 'describe': '在几分钟内设计您的Logo'},
                    {'name': 'Markdown', 'url': 'https://markdown.com.cn/editor/',
                     'describe': '微信公众号排版工具'},
                    {'name': '加速器', 'url': 'https://aff.mosucloud.host/aff.php?aff=1361', 'describe': 'VPN'},
                    {'name': 'Python开源项目搜索', 'url': 'https://www.programcreek.com/python/?action=search_project',
                     'describe': '开源辅助网站programcreek'},
                    {'name': '创建README', 'url': 'https://readme.so/', 'describe': '允许您快速添加和自定义项目自述文件所需的所有部分'},
                    {'name': '开发小工具', 'url': 'https://smalldev.tools/',
                     'describe': '这是一个便捷的开发工具，提供20多个工具，帮助开发人员完成编码/解码、缩小、测试虚拟数据集等常见任务。'},
                    ]

        Toolkit.objects.bulk_create([Toolkit(**toolkit, created_by=kwargs['admin']) for toolkit in toolkits],
                                    batch_size=50)

    def init_folder(self, **kwargs):
        folder = Folder.objects.create(name='一级目录', created_by=kwargs['demo'])  # 根节点
        Folder.objects.create(name='二级目录-1', parent=folder, created_by=kwargs['demo'])
        folder2 = Folder.objects.create(name='二级目录-2', parent=folder, created_by=kwargs['demo'])  # 子节点
        Folder.objects.create(name='三级目录-2-1', parent=folder2, created_by=kwargs['demo'])  # 子节点、叶子节点
        folder3 = Folder.objects.create(name='二级目录-3', parent=folder, created_by=kwargs['demo'])

        tags = Tag.objects.bulk_create([Tag(name=name) for name in ['Django', 'Python', '设计模式', '数据结构']])

        for i in range(50):
            article = Article.objects.create(title=fake.sentence(), abstract=fake.paragraph(),
                                             content=fake.text(),
                                             created_by=kwargs['demo'],
                                             folder=folder3,
                                             cover=f'article/0-{i}.jpg',
                                             status=Article.STATUS.published)

            article.tags.add(*random.sample(tags, 2))

    def init_iconfont(self, **kwargs):
        # 读取
        file_path = os.path.join(ROOT_DIR, 'const/iconfont.json')
        with open(file_path, encoding='utf-8') as fp:
            data = json.load(fp)
            glyphs = data['glyphs']
            Iconfont.objects.filter().delete()  # 重置
            Iconfont.objects.bulk_create(
                [Iconfont(name=icon['name'], font_class=icon['font_class']) for icon in glyphs], batch_size=200)
